package com.zd.lib.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;


/**
 * Created by zoudong on 16/8/22.
 */

public class KeyboardUtils {
    private static final String SHARE_PREFERENCE_NAME = "keyboard";
    private static final String SHARE_PREFERENCE_SOFT_INPUT_HEIGHT = "soft_input_height";
    private Activity mActivity;
    private InputMethodManager mInputManager;//软键盘管理类
    private SharedPreferences sp;
    private   boolean isShowInput=false; //是否显示输入法
    /**
     * 外部静态调用
     * @param activity
     * @return
     */
    public static KeyboardUtils with(Activity activity) {
        KeyboardUtils showHideUtils = new KeyboardUtils();
        showHideUtils.mActivity = activity;
        showHideUtils.mInputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        showHideUtils.sp = activity.getSharedPreferences(SHARE_PREFERENCE_NAME, Context.MODE_PRIVATE);
        return showHideUtils.init();
    }

    public KeyboardUtils init(){
        //设置软件盘的模式：SOFT_INPUT_ADJUST_RESIZE  这个属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        //从而方便我们计算软件盘的高度
        //  当设置了  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //  SOFT_INPUT_ADJUST_RESIZE  无效果
        mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        final  View decorView = mActivity.getWindow().getDecorView();
//        decorView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                decorView.postDelayed(new InputRunnable(isSoftInputShow()), 100);
//            }
//        });
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!isShowInput && isSoftInputShow()) {
                    isShowInput = true;
                    if (showHideListener != null) {
                        showHideListener.softStatue(isShowInput);
                    }
                } else if (isShowInput && !isSoftInputShow()) {
                    isShowInput = false;
                    if (showHideListener != null) {
                        showHideListener.softStatue(isShowInput);
                    }
                }
            }
        });
        return this;
    }
    private  class InputRunnable implements Runnable {
        private boolean isshow=true;

        public InputRunnable(boolean isshow) {
            this.isshow = isshow;
        }

        @Override
        public void run() {
            if (isshow!=isShowInput) {
                isShowInput =isshow;
                if (showHideListener != null) {
                    showHideListener.softStatue(isShowInput);
                }
            }

        }
    }

    /**
     * 是否显示软件盘
     * @return
     */
    private boolean isSoftInputShow() {
        return getSupportSoftInputHeight() != 0;
    }

    /**
     * 获取软件盘的高度
     * @return
     */
    private int getSupportSoftInputHeight() {
        Rect r = new Rect();
        /**
         * decorView是window中的最顶层view，可以从window中通过getDecorView获取到decorView。
         * 通过decorView获取到程序显示的区域，包括标题栏，但不包括状态栏。
         */
        mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        //获取屏幕的高度
        int screenHeight = mActivity.getWindow().getDecorView().getRootView().getHeight();
        //计算软件盘的高度
        int softInputHeight = screenHeight - r.bottom;

        /**
         * 某些Android版本下，没有显示软键盘时减出来的高度总是144，而不是零，
         * 这是因为高度是包括了虚拟按键栏的(例如华为系列)，所以在API Level高于20时，
         * 我们需要减去底部虚拟按键栏的高度（如果有的话）
         */
        if (Build.VERSION.SDK_INT >= 20) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight();
        }

        if (softInputHeight < 0) {
            LogUtils.w("showhinde","EmotionKeyboard--Warning: value of softInputHeight is below zero!");
        }
        //存一份到本地
        if (softInputHeight > 0) {
            sp.edit().putInt(SHARE_PREFERENCE_SOFT_INPUT_HEIGHT, softInputHeight).apply();
        }
        return softInputHeight;
    }

    public void setShowHideListener(SoftShowHideListener showHideListener) {
        this.showHideListener = showHideListener;
    }

    /**
     * 底部虚拟按键栏的高度
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private int getSoftButtonsBarHeight() {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        mActivity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }
     SoftShowHideListener showHideListener;
    public interface  SoftShowHideListener{
        void  softStatue(boolean isShow);
    }
}
